﻿using System.Text.RegularExpressions;
using Foothill.Common;
using Foothill.Model;

namespace Foothill.Service.Validation
{
    public class ValidationService : IValidationService
    {
        private IHtmlSanitizer _htmlSanitizer;

        public ValidationService(IHtmlSanitizer htmlSanitizer)
        {
            _htmlSanitizer = htmlSanitizer;
        }
        
        public bool ValidateEmailAddress(string str)
        {
            if (string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str))
            {
                return false;
            }

            string pattern = @"^[A-Za-z0-9_\-\.]+@(([A-Za-z0-9\-])+\.)+([A-Za-z\-])+$";
            Regex regex = new Regex(pattern);
            return regex.IsMatch(str);
        }

        // password cannot be empty and must be within length range
        public bool ValidatePassword(string pwd, out PasswordFormatError errorEnum)
        {
            errorEnum = PasswordFormatError.None;
            if (string.IsNullOrWhiteSpace(pwd))
            {
                errorEnum = PasswordFormatError.IsEmpty;
                return false;
            }

            if (pwd.Length > GlobalSettings.PasswordMaxLength)
            {
                errorEnum = PasswordFormatError.TooLong;
                return false;
            }

            if (pwd.Length < GlobalSettings.PasswordMinLength)
            {
                errorEnum = PasswordFormatError.TooShort;
                return false;
            }

            return true;
        }

        public string SanitizeHtml(string html)
        {
            string[] whitelist = { "a","abbr","acronym","address","b","big","blockquote","body","br",
                "caption","cite","col","colgroup","div","em","fieldset","h1","h2","h3","h4","h5","h6","hr","i","label","legend","li","ol","p","pre","small",
                "span","strong","style","sub","sup","table","tbody","td","textarea","tfoot","th",
                "thead","title","tr","tt","ul" };
            return _htmlSanitizer.SanitizeHtmlText(html, whitelist);
        }
    }
}
